package com.innovation.chengzhangriji.ui;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.hardware.Camera;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;

import com.innovation.chengzhangriji.Config;
import com.innovation.chengzhangriji.R;
import com.innovation.chengzhangriji.ui.widget.CameraPreview;
import com.innovation.chengzhangriji.ui.widget.CuteImageView;
import com.umeng.analytics.MobclickAgent;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class HeadCameraActivity extends BaseActivity implements View.OnClickListener {

    private static final String TAG = CameraActivity.class.getSimpleName();

    public static final int MEDIA_TYPE_IMAGE = 1;
    public static final int MEDIA_TYPE_VIDEO = 2;

    private Camera mCamera;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_head_camera);
        // Create an instance of Camera
        mCamera = getCameraInstance();
        // Create our Preview view and set it as the content of our activity.
        CameraPreview cameraPreview = new CameraPreview(this, mCamera);
        FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
        preview.addView(cameraPreview);
        CuteImageView button = (CuteImageView) findViewById(R.id.button_camera);
        button.setOnClickListener(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        releaseCamera();
    }

    @Override
    protected void onPageStart() {
        MobclickAgent.onPageStart(Config.UMENG_PAGE_CAMERA);
    }

    @Override
    protected void onPageEnd() {
        MobclickAgent.onPageEnd(Config.UMENG_PAGE_CAMERA);
    }

    @Override
    public void onClick(View v) {
        mCamera.takePicture(null, null, mPicture);
    }

    /**
     * A safe way to get an instance of the Camera object.
     */
    public static Camera getCameraInstance() {
        Camera c = null;
        try {
            c = Camera.open(); // attempt to get a Camera instance
        } catch (Exception e) {
            // Camera is not available (in use or does not exist)
        }
        return c; // returns null if camera is unavailable
    }

    private Camera.PictureCallback mPicture = new Camera.PictureCallback() {

        @Override
        public void onPictureTaken(byte[] data, Camera camera) {
            File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
            if (pictureFile == null) {
                /*Log.d(TAG, "Error creating media file, check storage permissions: " +
                        e.getMessage());*/
                return;
            }
            Bitmap bm = null, rotatedBitmap = null;
            try {
                BitmapFactory.Options opt;
                opt = new BitmapFactory.Options();
                opt.inTempStorage = new byte[16 * 1024];
                Camera.Parameters parameters = camera.getParameters();
                Camera.Size size = parameters.getPictureSize();
                int height11 = size.height;
                int width11 = size.width;
                float mb = (width11 * height11) / 1024000;
                if (mb > 4f)
                    opt.inSampleSize = 4;
                else if (mb > 3f)
                    opt.inSampleSize = 2;
                bm = BitmapFactory.decodeByteArray(data, 0, data.length, opt);
                Matrix matrix = new Matrix();
                matrix.postRotate(90);
                rotatedBitmap = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, true);
                FileOutputStream fos = new FileOutputStream(pictureFile);
                rotatedBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
                fos.flush();
                fos.close();
            } catch (FileNotFoundException e) {
                Log.d(TAG, "File not found: " + e.getMessage());
            } catch (IOException e) {
                Log.d(TAG, "Error accessing file: " + e.getMessage());
            } finally {
                if(bm != null && !bm.isRecycled()) {
                    bm.recycle();
                }
                bm = null;
                if(rotatedBitmap != null && !rotatedBitmap.isRecycled()) {
                    rotatedBitmap.recycle();
                }
                rotatedBitmap = null;
            }
            galleryAddPic(pictureFile);
            resultPath(pictureFile.getPath());
        }
    };

    /**
     * Create a File for saving an image or video
     */
    public static File getOutputMediaFile(int type) {
        // To be safe, you should check that the SDCard is mounted
        // using Environment.getExternalStorageState() before doing this.

        File mediaStorageDir = new File(Environment.getExternalStorageDirectory() + "/ChZhRJ/", "Images");
        // This location works best if you want the created images to be shared
        // between applications and persist after your app has been uninstalled.

        // Create the storage directory if it does not exist
        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                Log.d("MyCameraApp", "failed to create directory");
                return null;
            }
        }

        // Create a media file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        File mediaFile;
        if (type == MEDIA_TYPE_IMAGE) {
            mediaFile = new File(mediaStorageDir.getPath() + File.separator +
                    "IMG_" + timeStamp + ".jpg");
        } else if (type == MEDIA_TYPE_VIDEO) {
            mediaFile = new File(mediaStorageDir.getPath() + File.separator +
                    "VID_" + timeStamp + ".mp4");
        } else {
            return null;
        }

        return mediaFile;
    }

    private void releaseCamera() {
        if (mCamera != null) {
            mCamera.release();        // release the camera for other applications
            mCamera = null;
        }
    }

    private void galleryAddPic(File f) {
        Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        Uri contentUri = Uri.fromFile(f);
        mediaScanIntent.setData(contentUri);
        this.sendBroadcast(mediaScanIntent);
    }

    public static final int CROP_INTENT = 0;
    private File cropImage;

    private void resultPath(String path) {
//        Intent resultIntent = new Intent();
//        resultIntent.putExtra(Config.ACTION_EXTERNAL_RESULT_PHOTO, path);
//        setResult(RESULT_OK, resultIntent);
//        finish();

        // 裁剪
        cropImage = HeadCameraActivity.getOutputMediaFile(MEDIA_TYPE_IMAGE);
        Intent intent = new Intent();
        intent.setAction("com.android.camera.action.CROP");
        intent.setDataAndType(Uri.fromFile(new File(path)), "image/*");   // mUri是已经选择的图片Uri
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);    // 裁剪框比例
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 120);  // 输出图片大小
        intent.putExtra("outputY", 120);
        intent.putExtra("return-data", false);
        intent.putExtra("scale", true);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cropImage));
        startActivityForResult(intent, CROP_INTENT);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if(resultCode == RESULT_OK && requestCode == HeadCameraActivity.CROP_INTENT) {
            Intent resultIntent = new Intent();
            resultIntent.putExtra(Config.ACTION_EXTERNAL_RESULT_PHOTO, cropImage.getAbsolutePath());
            setResult(RESULT_OK, resultIntent);
        }
        finish();
    }
}
